package modulelib

import "time"

//TimeTicker 定时器服务
type TimeTicker struct {
	timer          *time.Ticker
	durMillisecond time.Duration
	isRunning      bool
	elapsed        func()
}

//Init 初始化定时器
func (_this *TimeTicker) Init(durMillisecond int64) {
	_this.isRunning = false
	_this.durMillisecond = time.Millisecond * time.Duration(durMillisecond)
}

//SetElapsed 设置定时器回调
func (_this *TimeTicker) SetElapsed(elapsed func()) {
	_this.elapsed = elapsed
}

//Start 启动定时器
func (_this *TimeTicker) Start() {
	_this.timer = time.NewTicker(time.Millisecond * time.Duration(_this.durMillisecond))
	_this.isRunning = true
	go func() {
		for _this.isRunning {
			<-_this.timer.C
			if !_this.isRunning {
				if _this.elapsed != nil {
					_this.elapsed()
				}
			} else {
				_this.timer.Stop()
				break
			}
		}
	}()
}

//Close 关闭定时器
func (_this *TimeTicker) Close() {
	_this.isRunning = false
}

//Stop 关闭定时器
func (_this *TimeTicker) Stop() {
	_this.timer.Stop()
}
